﻿using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;

namespace Back_end.APIHelper
{
    [EnableCors("*", "*", "POST,GET")]
	[RoutePrefix("api/Helper")]
	// [Authorize]
	public class HelperApiController : ApiController
	{
		[AllowAnonymous]
		[Route("UploadPicture")]
		public Task<Hashtable> UploadPicture()
		{
			// 检查是否是 multipart/form-data 
			if (!Request.Content.IsMimeMultipartContent("form-data"))
				throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
			//文件保存目录路径 
			string SaveTempPath = "/Image/Upload";
			string dirTempPath = HttpContext.Current.Server.MapPath(SaveTempPath);
			// 设置上传目录 
			var provider = new MultipartFormDataStreamProvider(dirTempPath);
			var task = Request.Content.ReadAsMultipartAsync(provider).
				ContinueWith<Hashtable>(o =>
				{
					Hashtable hash = new Hashtable();
					hash["error"] = 1;
					hash["msg"] = "";

					if (provider.FileData.Count == 0)
						return hash;
					var file = provider.FileData[0];
					//foreach (var file in provider.FileData)
					//{
					string orfilename = file.Headers.ContentDisposition.FileName.TrimStart('"').TrimEnd('"');
					FileInfo fileinfo = new FileInfo(file.LocalFileName);
					//最大文件大小 
					int maxSize = 10500000;
					if (fileinfo.Length <= 0)
					{
						hash["error"] = 1;
						hash["msg"] = "请选择上传文件。";
						//break;
					}
					else if (fileinfo.Length > maxSize)
					{
						hash["error"] = 1;
						hash["msg"] = "上传文件大小超过限制。";
						//break;
					}
					else
					{
						string fileExt = orfilename.Substring(orfilename.LastIndexOf('.'));
						//定义允许上传的文件扩展名 
						string fileTypes = "jpg,jpeg";
						if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
						{
							hash["error"] = 1;
							hash["msg"] = "上传文件扩展名是不允许的扩展名。";
							//break;
						}
						else
						{
							// string ymd = DateTime.Now.ToString("yyyyMMdd", System.Globalization.DateTimeFormatInfo.InvariantInfo);
							string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", System.Globalization.DateTimeFormatInfo.InvariantInfo);
							fileinfo.CopyTo(Path.Combine(dirTempPath, newFileName + fileExt), true);
							hash["error"] = 0;
							hash["msg"] += ("/Image/Upload/" + newFileName + fileExt + "g");
							fileinfo.Delete();
						}
					}
					//}
					if (((int)hash["error"]) == 0)
					{
						var files = hash["msg"].ToString();
						hash["msg"] = files.Remove(files.Length - 1);
					}
					return hash;
				});
			return task;
		}
	}
}
